import { defineStore } from 'pinia';
import { api } from '../services/api';

export const useCardStore = defineStore('card', {
  state: () => ({
    cards: {},
    loading: false,
    error: null
  }),
  
  actions: {
    async fetchCard(cardId) {
      this.loading = true;
      try {
        const card = await api.get(`/cards/${cardId}`);
        this.cards[cardId] = card;
      } catch (error) {
        this.error = error.message;
      } finally {
        this.loading = false;
      }
    },

    async updateCard({ id, ...updates }) {
      try {
        const updatedCard = await api.put(`/cards/${id}`, updates);
        this.cards[id] = updatedCard;
      } catch (error) {
        this.error = error.message;
      }
    },

    async moveCard({ cardId, listId, position }) {
      try {
        await api.post(`/cards/${cardId}/move`, { listId, position });
      } catch (error) {
        this.error = error.message;
      }
    },

    async addAttachment(cardId, file) {
      const formData = new FormData();
      formData.append('file', file);
      
      try {
        const attachment = await api.post(
          `/cards/${cardId}/attachments`, 
          formData,
          {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }
        );
        
        if (!this.cards[cardId].attachments) {
          this.cards[cardId].attachments = [];
        }
        this.cards[cardId].attachments.push(attachment);
      } catch (error) {
        this.error = error.message;
      }
    }
  }
}); 